package com.yamin.picToCharPaint.utils.image.impl;

import com.yamin.picToCharPaint.utils.image.AbstractImage;
import com.yamin.picToCharPaint.utils.image.IPicToStrPic;
import com.madgag.gif.fmsware.AnimatedGifEncoder;
import com.madgag.gif.fmsware.GifDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.awt.image.BufferedImage;
import java.io.*;
import java.util.UUID;

/**
 * @description:
 * @author：yamin
 * @date: 2021/9/15
 */
@Component("gifUtil")
public class GifUtil extends AbstractImage implements IPicToStrPic {

    private final Logger logger = LoggerFactory.getLogger(GifUtil.class);


    /**
     * 输入流
     *
     * @param inputStream 输入流
     * @param precision   精度
     */
    private void gifToStr(InputStream inputStream, int precision) {
        logger.info("开始转换GIF");
        //创建 GIF 解析器
        GifDecoder decoder = new GifDecoder();
        //判断流是否读取成功
        int status = decoder.read(inputStream);
        if (status != GifDecoder.STATUS_OK) {
            logger.info("读取输入流失败");
            return;
        }
        //创建 GIF 合成器
        AnimatedGifEncoder encoder = new AnimatedGifEncoder();

        encoder.setRepeat(0);
        //创建gif文件
        String fileName = UUID.randomUUID() + ".gif";
        //开始写入数据到 GIF 文件
        encoder.start(fileName);
        //获取 GIF 文件的帧数
        int count = decoder.getFrameCount();
        for (int i = 0; i < count; i++) {
            //获取 GIF 当前帧数
            BufferedImage frame = decoder.getFrame(i);
            //获取 GIF 当前延时时间
            int delay = decoder.getDelay(i);
            String base64;
            BufferedImage pic = null;
            //对当前帧数进行加工
            try {
                base64 = this.picToBase64(frame, precision, "jpg");
                pic = this.base64ToPic(base64);
            } catch (IOException e) {
                logger.error("GIF帧转换失败，帧：{}", count, e);
            }
            //添加帧到新的 GIF 文件中
            encoder.addFrame(pic);
            //添加延时时间到新的 GIF 文件中
            encoder.setDelay(delay);
        }
        //新的 GIF 创建完成
        encoder.finish();
        logger.info("转换成功，文件名：{}", fileName);

    }

    @Override
    public void toStrPic(InputStream inputStream, int precision, String formatName) {
        gifToStr(inputStream, precision);
    }


}
